<template>
  <!-- 登录 -->
  <div class="login w-full h-full">
    <el-form
      ref="formRef"
      class="w-[320px] p-10 absolute top-[40%] -translate-y-1/2 left-20"
      :model="form"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="旧密码" prop="password">
        <el-input
          type="password"
          v-model="form.oldPassword"
          placeholder="请输旧密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="password"
          v-model="form.newPassword"
          placeholder="请输入新密码"
        />
      </el-form-item>

      <el-form-item>
        <div class="w-full relative">
          <router-link to="/login" class="block text-blue-700 text-right mb-2">
            去登录
          </router-link>
          <el-button
            class="flex-1 w-full"
            type="primary"
            @click="handleUpdatePassword"
          >
            注册
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage, type FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { request } from "../../utils/request";
import { updatePassword } from "../../api";
import { useRouter } from "vue-router";

interface Form {
  account: string;
  oldPassword: string;
  newPassword: string;
}

const form = reactive<Form>({
  account: "",
  oldPassword: "",
  newPassword: "",
});
const rules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  oldPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
  ],
};
const formRef = ref<FormInstance>();
const router = useRouter();

function handleUpdatePassword() {
  formRef.value?.validate((valid) => {
    if (!valid) return;
    request({
      fn: updatePassword,
      params: [form],
      success() {
        ElMessage.success("修改成功");
        router.push("/login");
      },
    });
  });
}
</script>
<style scoped lang="scss">
.login {
  background: url("../../assets/images/login_bg.png") no-repeat center center;
  background-size: cover;
}
</style>
